﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.UI.Models;
using System.Windows.Input;
using ARR.Shared;
using System.Collections.ObjectModel;
using ARR.Entities;
using System.Windows;
using ARR.UI.Commands;
using ARR.UI.EnvoyImporterService;
using ARR.UI.ArticlesService;
using ARR.UI.ExcelImporterService;
using System.ServiceModel;
using ARR.UI.Views;

namespace ARR.UI.ViewModels
{
    public class InventoriesImporterViewModel : WorkspaceViewModel
    {
        public IInventoriesImporterModel model;
        private ICommand cancelCommand;
        private ICommand nextCommand;
        private ICommand retryCommand;
        private ICommand startCommand;
        private ICommand missingArticlesCommand;



        public InventoriesImporterViewModel(IInventoriesImporterModel model)
        {
            base.DisplayName = Labels.ImportadorDeInventarios;
            this.model = model;

            CurrentStep = 0;
        }



        public ICommand NextCommand
        {
            get
            {
                if (nextCommand == null)
                {
                    nextCommand = new RelayCommand(param => NextStep(), p => (HasPassedCurrentStep.HasValue && HasPassedCurrentStep.Value && CurrentStep != 4));
                }
                return nextCommand;
            }
        }

        public ICommand RetryCommand
        {
            get
            {
                if (retryCommand == null)
                {
                    retryCommand = new RelayCommand(param => RetryCurrentStep(), p => (HasPassedCurrentStep.HasValue && !HasPassedCurrentStep.Value));
                }
                return retryCommand;
            }
        }

        public ICommand StartCommand
        {
            get
            {
                if (startCommand == null)
                {
                    startCommand = new RelayCommand(param => NextStep(), p => CurrentStep == 0);

                }
                return startCommand;
            }
        }
                
        public ICommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new RelayCommand(param => Cancel());
                }
                return cancelCommand;
            }
        }

        public ICommand MissingArticlesCommand
        {
            get
            {
                if (missingArticlesCommand == null)
                {
                    missingArticlesCommand = new RelayCommand(param => OpenMissingArticlesPopup());
                }
                return missingArticlesCommand;
            }
        }
       


        public ObservableCollection<ImporterResult> Results
        {
            get
            {
                return new ObservableCollection<ImporterResult>(model.Results.OrderBy(x => x.Description));
            }
        }

        public ObservableCollection<TempInventory> TempInventories
        {
            get
            {
                return model.TempInventories;
            }
        }

        public Visibility IsVisibleResultsGV
        {
            get
            {
                if (Results != null && Results.Any())
                {
                    return Visibility.Visible;
                }

                return Visibility.Collapsed;
            }
        }

        public Visibility IsVisibleTempInventoriesGV
        {
            get
            {
                if (TempInventories != null && TempInventories.Any())
                {
                    return Visibility.Visible;
                }

                return Visibility.Collapsed;
            }
        }

        public string Step1ImagePath { get; set; }

        public string Step2ImagePath { get; set; }

        public string Step3ImagePath { get; set; }

        public string Step4ImagePath { get; set; }

        public int CurrentStep { get; set; }

        public bool? HasPassedCurrentStep { get; set; }

        public bool IsBusy { get; set; }



        public void TriggerPropertyChanged()
        {
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.TempInventories);
        }


        private void OpenMissingArticlesPopup()
        {
            MissingArticlesPopupView popup = new MissingArticlesPopupView();
            popup.DataContext = new MissingArticlesPopupViewModel();

            bool? res = popup.ShowDialog();

            if (res.HasValue && res.Value)
            {
                RetryCurrentStep();
            }
        }

        private void Cancel()
        {

        }

        private void NextStep()
        {
            switch (CurrentStep)
            {
                case 0:
                    RunStep1();
                    break;
                case 1:
                    RunStep2();
                    break;
                case 2:
                    RunStep3();
                    break;
                case 3:
                    RunStep4();
                    break;
            }


            OnPropertyChanged<InventoriesImporterViewModel>(p => p.Results);
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleResultsGV);

            if (CurrentStep < 4)
                CurrentStep += 1;
        }

        private void RetryCurrentStep()
        {
            CurrentStep -= 1;
            NextStep();
        }

        private void RunStep1()
        {
            switch (WorkspaceData.Instance.Country.StoresImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;
                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.ImportInventoryMasterStep1Completed += new EventHandler<ExcelImporterService.ImportInventoryMasterStep1CompletedEventArgs>(excelService_ImportInventoryMasterStep1Completed);
                            excelService.ImportInventoryMasterStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;
                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.ImportInventoryMasterStep1Completed += new EventHandler<EnvoyImporterService.ImportInventoryMasterStep1CompletedEventArgs>(client_ImportInventoryMasterStep1Completed);
                            envoyService.ImportInventoryMasterStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }


            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);

        }

        private void RunStep2()
        {
            switch (WorkspaceData.Instance.Country.StoresImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;
                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.ImportInventoryMasterStep2Completed += new EventHandler<ExcelImporterService.ImportInventoryMasterStep2CompletedEventArgs>(excelService_ImportInventoryMasterStep2Completed);
                            excelService.ImportInventoryMasterStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;
                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.ImportInventoryMasterStep2Completed += new EventHandler<EnvoyImporterService.ImportInventoryMasterStep2CompletedEventArgs>(client_ImportInventoryMasterStep2Completed);
                            envoyService.ImportInventoryMasterStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }


            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);
        }

        private void RunStep3()
        {
            EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

            try
            {
                envoyService.ImportInventoryMasterStep3Completed += new EventHandler<EnvoyImporterService.ImportInventoryMasterStep3CompletedEventArgs>(client_ImportInventoryMasterStep3Completed);
                envoyService.ImportInventoryMasterStep3Async(WorkspaceData.Instance.RangeReview);
            }
            catch (Exception ex)
            {
                envoyService.Abort();
                throw ex;
            }
            
            IsBusy = true;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);

        }

        private void RunStep4()
        {
            EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

            try
            {
                envoyService.ImportInventoryMasterStep4Completed += new EventHandler<EnvoyImporterService.ImportInventoryMasterStep4CompletedEventArgs>(client_ImportInventoryMasterStep4Completed);
                envoyService.ImportInventoryMasterStep4Async(WorkspaceData.Instance.RangeReview);
            }
            catch (Exception ex)
            {
                envoyService.Abort();
                throw ex;
            }

            IsBusy = true;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);
        }


        void excelService_ImportInventoryMasterStep1Completed(object sender, ExcelImporterService.ImportInventoryMasterStep1CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step1ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step1ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }
                }

                OnPropertyChanged<InventoriesImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Step1ImagePath);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Results);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }

        void excelService_ImportInventoryMasterStep2Completed(object sender, ExcelImporterService.ImportInventoryMasterStep2CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step2ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step2ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }
                }

                OnPropertyChanged<InventoriesImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Step2ImagePath);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Results);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }


        void client_ImportInventoryMasterStep1Completed(object sender, EnvoyImporterService.ImportInventoryMasterStep1CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step1ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step1ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }
                }

                OnPropertyChanged<InventoriesImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Step1ImagePath);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Results);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }

        void client_ImportInventoryMasterStep2Completed(object sender, EnvoyImporterService.ImportInventoryMasterStep2CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step2ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step2ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }
                }

                OnPropertyChanged<InventoriesImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Step2ImagePath);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Results);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }

        void client_ImportInventoryMasterStep3Completed(object sender, EnvoyImporterService.ImportInventoryMasterStep3CompletedEventArgs e)
        {
            (sender as ICommunicationObject).Close();

            model.Results = e.Result;

            Step3ImagePath = "/Images/Pass-16.png";
            HasPassedCurrentStep = true;

            if (model.Results.Any())
            {
                if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                {
                    Step3ImagePath = "/Images/NotPass-16.png";
                    HasPassedCurrentStep = false;
                }

                if (model.Results.Any(r => r.ItemId != 0))
                {
                    
                }
            }
            else
            {
                model.TempInventories.Clear();
            }

            IsBusy = false;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.HasPassedCurrentStep);
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.Step3ImagePath);
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.TempInventories);
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.Results);
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleTempInventoriesGV);
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleResultsGV);
        }

        void client_ImportInventoryMasterStep4Completed(object sender, EnvoyImporterService.ImportInventoryMasterStep4CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step4ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step4ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }
                }

                IsBusy = false;
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsBusy);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Step4ImagePath);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.Results);
                OnPropertyChanged<InventoriesImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }
            
        }

    }
}
